import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.junit.Test;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyBatisGenerate {

    @Test
    public void generate() throws NoSuchFieldException, IllegalAccessException {

        // 基本模块参数
        String modelModuleName = "iweb-model";
        String mapperModuleName = "iweb-mapper";
        String serviceModuleName = "iweb-service";
        String webModuleName = "iweb-web";
        // 基本包参数
        String baseController = "com.iweb.controller";
        String baseService = "com.iweb.service";
        String baseServiceImpl = "com.iweb.service.impl";
        String baseMapper = "com.iweb.mapper";
        String baseModel = "com.iweb.model";

        String url = "jdbc:mysql://192.168.100.129:3306/iweb-isdn?useUnicode=true&characterEncoding=UTF-8" +
                "&zeroDateTimeBehavior=convertToNull";
        // 基本包
        String baseDir = System.getProperty("user.dir");
        String driverClassName = "com.mysql.cj.jdbc.Driver";
        String username = "root";
        String password = "123456";

        // 表 前缀
        String[] tablePrefix = new String[]{"tb_"};
        // 需要逆向的表
        String[] tableNames = new String[]{"tb_article", "tb_channel", "tb_member", "tb_notice"};

        /*数据源*/
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);
        dsc.setUrl(url);
        dsc.setDriverName(driverClassName);
        dsc.setUsername(username);
        dsc.setPassword(password);

        /*全局配置*/
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(baseDir + "/src/main/java");
        gc.setFileOverride(true);
        gc.setActiveRecord(true);
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(true);// XML columList
        gc.setAuthor("jack");
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setControllerName("%sController");

        /*生成策略*/
        StrategyConfig strategy = new StrategyConfig();
        strategy.setEntityLombokModel(true);
        strategy.setEntityTableFieldAnnotationEnable(true);
        strategy.setTablePrefix(tablePrefix);// 此处可以修改为您的表前缀
        strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
        strategy.setInclude(tableNames); // 需要生成的表

        /*生成文件包配置*/
        PackageConfig pc = new PackageConfig();
//        pc.setParent(parentPackage);
//        pc.setController("controller");
//        pc.setService("service");
//        pc.setServiceImpl("service.impl");
//        pc.setEntity("model");
//        pc.setMapper("mapper");

        AutoGenerator mpg = new AutoGenerator();

        /*xml文件配置*/
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // nothing
            }
        };
        //xml生成路径
        List<FileOutConfig> focList = new ArrayList<>();
        focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return baseDir + "/" + mapperModuleName + "/src/main/resources/" + "/mapper/" + tableInfo.getEntityName() +
                        "Mapper.xml";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 关闭默认 xml 生成，调整生成 至 根目录
        TemplateConfig tc = new TemplateConfig();
        tc.setXml(null);
        tc.setController("");

        mpg.setDataSource(dsc);         //数据源配置
        mpg.setGlobalConfig(gc);        //全局配置
        mpg.setStrategy(strategy);      //生成策略配置
        mpg.setPackageInfo(pc);         //包配置
        mpg.setCfg(cfg);                //xml配置
        mpg.setTemplate(tc);            //


        /*自定义输出路径*/
        Map<String, String> packageInfo = new HashMap<>();
        packageInfo.put(ConstVal.CONTROLLER, baseController);
        packageInfo.put(ConstVal.SERVICE, baseService);
        packageInfo.put(ConstVal.SERVICE_IMPL, baseServiceImpl);
        packageInfo.put(ConstVal.ENTITY, baseModel);
        packageInfo.put(ConstVal.MAPPER, baseMapper);

        Map<String, String> pathInfo = new HashMap<>();
        pathInfo.put(ConstVal.CONTROLLER_PATH,
                baseDir + "/" + webModuleName + "/src/main/java/" + baseController.replaceAll("\\.", "/"));
        pathInfo.put(ConstVal.SERVICE_PATH,
                baseDir + "/" + serviceModuleName + "/src/main/java/" + baseService.replaceAll("\\.", "/"));
        pathInfo.put(ConstVal.SERVICE_IMPL_PATH,
                baseDir + "/" + serviceModuleName + "/src/main/java/" + baseServiceImpl.replaceAll("\\.", "/"));
        pathInfo.put(ConstVal.ENTITY_PATH,
                baseDir + "/" + modelModuleName + "/src/main/java/" + baseModel.replaceAll("\\.", "/"));
        pathInfo.put(ConstVal.MAPPER_PATH,
                baseDir + "/" + mapperModuleName + "/src/main/java/" + baseMapper.replaceAll("\\.", "/"));
        pathInfo.put(ConstVal.XML_PATH, baseDir + "/" + mapperModuleName + "/src/main/resources/mapper");
        pc.setPathInfo(pathInfo);

        ConfigBuilder configBuilder = new ConfigBuilder(mpg.getPackageInfo(), mpg.getDataSource(),
                mpg.getStrategy(),
                mpg.getTemplate(), mpg.getGlobalConfig());
        Field packageInfoField = configBuilder.getClass().getDeclaredField("packageInfo");
        packageInfoField.setAccessible(true);
        packageInfoField.set(configBuilder, packageInfo);
        mpg.setConfig(configBuilder);
        /*自定义输出路径结束*/
        // 执行生成
        mpg.execute();
    }

}
